import { CreatePermissionDto } from "@/examples/permission/dto/create-permission.dto";
import { plainToInstance, Transform, Type } from "class-transformer";
import { IsArray, IsNotEmpty, IsOptional, IsString } from "class-validator";

interface PermissionType {
    id?: number;
    name: string;
    action: string;
    description?: string;
}

abstract class Permission {
    abstract type: string;
}

class StringPermission implements Permission {
    type = 'string';
    value: string;
}

class DetailedPermission implements Permission {
    type = 'detailed';
    name: string;
    action: string;
}


export class CreateRoleDto {
    @IsNotEmpty()
    @IsString()
    name: string;

    @IsOptional()
    @IsString()
    description?: string;

    @IsOptional()
    @IsArray()
    // @Type(() => CreatePermissionDto)  // 这个是简化的写法，但是无法处理两种类型
    @Type(() => Permission, {       // 这里是完整的写法，可以处理两种类型
        discriminator: {
            property: 'type',
            subTypes: [
                { value: StringPermission, name: 'permission' },
                { value: DetailedPermission, name: 'detail' },
            ],
        }
    })
    // 两种类型1.string[] 2.对象[]
    // 当传递为string -> split -> {name, action}对象数组
    // 当传递为对象 -> 直接转换成对呀的dto实例
    @Transform(({ value }) => {
        return value.map((item: any) => {
            if (typeof item === 'string') {
                const parts = item.split(':');
                return plainToInstance(CreatePermissionDto, { name: item, action: parts[1] || '' });
            }
            return plainToInstance(CreatePermissionDto, item);
        })
    })
    permissions: PermissionType[] | string[];
}
